package com.thinkit.security.custom;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.thinkit.nosql.base.BaseRedisService;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Date;

public class CustomJwtTokenStore extends JwtTokenStore {

    @Autowired
    BaseRedisService baseRedisService;

    public static final String auth="auth::";

    public CustomJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
    }

    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        if (token.getAdditionalInformation().containsKey("jti")) {
            String jti = token.getAdditionalInformation().get("jti").toString();
            String userId = token.getAdditionalInformation().get("userId").toString();
            Date date = token.getExpiration();
            if(Checker.BeNotNull(date)){
                Long exp =  DateUtil.between(date,new Date(), DateUnit.SECOND);
                baseRedisService.set(auth+userId,jti,exp);
            }else{
                baseRedisService.set(auth+userId,jti);
            }
        }
        super.storeAccessToken(token, authentication);
    }

    @Override
    public void removeAccessToken(OAuth2AccessToken token) {
        if (token.getAdditionalInformation().containsKey("jti")) {
            //String jti = token.getAdditionalInformation().get("jti").toString();
            String userId = token.getAdditionalInformation().get("userId").toString();
            baseRedisService.remove(auth+userId);
        }
        super.removeAccessToken(token);
    }
}
